package com.foreveross.fetl.core.domain.freight;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Query;
import javax.persistence.Table;

import org.springframework.transaction.annotation.Transactional;

import com.dayatang.domain.InstanceFactory;
import com.foreveross.fetl.common.domain.BaseEntity;
import com.foreveross.fetl.core.domain.freight.repository.IFetlDataRepository;

@Entity
@Table(name = "fdc_fetl_data")
public class FetlDataEntity extends BaseEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Integer id;

	@Column(name = "ATTACH_HBASE_KEY")
	private String attachHbaseKey;

	@Column(name = "FROM_CITY")
	private String fromCity; // 时间

	@Column(name = "TO_CITY")
	private String toCity;// 路径

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getAttachHbaseKey() {
		return attachHbaseKey;
	}

	public void setAttachHbaseKey(String attachHbaseKey) {
		this.attachHbaseKey = attachHbaseKey;
	}

	public String getFromCity() {
		return fromCity;
	}

	public void setFromCity(String fromCity) {
		this.fromCity = fromCity;
	}

	public String getToCity() {
		return toCity;
	}

	public void setToCity(String toCity) {
		this.toCity = toCity;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public IFetlDataRepository getFetlDataRepository() {
		return InstanceFactory.getInstance(IFetlDataRepository.class);
	}

	@Transactional
	public void saveOrUpdate(FetlDataEntity entity) {

		if (null == entity.getAttachHbaseKey()) {
			throw new IllegalArgumentException("渠道不能为空");
		}
		if (null == entity.getFromCity()) {
			throw new IllegalArgumentException("出发城市不能为空");
		}
		if (null == entity.getToCity()) {
			throw new IllegalArgumentException("到达城市不能为空");
		}
		List list = entity
				.createQuery(
						"SELECT COUNT(a) FROM FetlDataEntity a WHERE a.attachHbaseKey=? and a.fromCity=? and a.toCity=?",
						new Object[] { entity.getAttachHbaseKey(),
								entity.getFromCity(), entity.getToCity() })
				.getResultList();
		if ((Long)list.get(0)==0) getFetlDataRepository().save(entity);
	}

	public List<FetlDataEntity> findByCondition(String channel,
			String fromCity, String toCity) {
		return getFetlDataRepository().findByCondition(channel, fromCity,
				toCity);
	}

	public Query createQuery(String hql, Object[] params) {
		return getFetlDataRepository().createQuery(hql, params);
	}

	public FetlDataEntity get(Integer id) {
		return getFetlDataRepository().find(FetlDataEntity.class, id);
	}
}
